package utils

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// 封装 HTTP 客户端
type HttpClient struct {
	baseURL string
	headers map[string]string
	timeout time.Duration
}

func NewHttpClient(baseURL string) *HttpClient {
	return &HttpClient{
		baseURL: baseURL,
		headers: make(map[string]string),
		timeout: 10 * time.Second,
	}
}

// 链式配置方法
func (h *HttpClient) SetHeader(key, value string) *HttpClient {
	h.headers[key] = value
	return h
}

func (h *HttpClient) SetTimeout(seconds int) *HttpClient {
	h.timeout = time.Duration(seconds) * time.Second
	return h
}

// 封装 GET 请求
func (h *HttpClient) Get(path string, params map[string]string) ([]byte, error) {
	client := &http.Client{Timeout: h.timeout}

	// 构建请求URL
	req, _ := http.NewRequest("GET", h.baseURL+path, nil)
	q := req.URL.Query()
	for k, v := range params {
		q.Add(k, v)
	}
	req.URL.RawQuery = q.Encode()

	// 添加请求头
	for k, v := range h.headers {
		req.Header.Add(k, v)
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return io.ReadAll(resp.Body)
}

// 封装 POST 请求（支持JSON和FormData）
func (h *HttpClient) Post(path string, data interface{}, contentType string) ([]byte, error) {
	client := &http.Client{Timeout: h.timeout}

	var body io.Reader
	switch contentType {
	case "json":
		jsonData, _ := json.Marshal(data)
		body = bytes.NewBuffer(jsonData)
		h.headers["Content-Type"] = "application/json"
	case "form":
		formData := url.Values{}
		for k, v := range data.(map[string]string) {
			formData.Add(k, v)
		}
		body = strings.NewReader(formData.Encode())
		h.headers["Content-Type"] = "application/x-www-form-urlencoded"
	}

	req, _ := http.NewRequest("POST", h.baseURL+path, body)

	// 添加请求头
	for k, v := range h.headers {
		req.Header.Add(k, v)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return io.ReadAll(resp.Body)
}
